﻿using UnityEngine;
using System.Collections;

public class Vehicle : MonoBehaviour {

	public float hull;
	public float speed;
	public float Reward = 10;
	public float lifeTimer;
	public float lifeTime = 1.5f;
	public bool hitByPlayer;
	public GameObject DestroyParticles;
	GameObject Parts;
	public AudioSource Explosion;
	public AudioSource Impact;
	public CameraShake Shaker;
	
	public PlayerStorage main;

	public delegate void VehicleDeathManager();
	public static event VehicleDeathManager vehicleDeath;
	
	void OnEnable()
	{
		main = GameObject.Find("MainService").GetComponent<PlayerStorage>();
		Shaker = GameObject.Find("Main Camera").GetComponent<CameraShake>();
		Explosion = GameObject.Find("Audio Source(Explosion)").GetComponent<AudioSource>();
		Impact = GameObject.Find("Audio Source(Impact)").GetComponent<AudioSource>();
	}
	
	void OnCollisionEnter(Collision col)
	{
		if (col.gameObject.GetComponent<PlayerVehicle>() != null)
		{
			hitByPlayer = true;
		}
		
		Shaker.shakeIt();
		Impact.Play();
		Obstacle obj_hit = col.gameObject.GetComponent<Obstacle>();
		float damage = obj_hit.Damage;
		hull +=  -damage;
		
	}
	
	
	
	
	void Update () 
	{
	
		transform.Translate(new Vector3( 0, 0, speed) * Time.deltaTime);
		
		if(hull <= 0)
		{
	
			
			lifeTimer += 1.0F * Time.deltaTime;
			
			
			if (lifeTimer > lifeTime)
			{
				if (hitByPlayer == true)
				{
					main.cash += Reward;
				}
			
				Explosion.Play();
				Destroy(gameObject);
				Parts = Instantiate (DestroyParticles, new Vector3(transform.position.x, transform.position.y+1.7f, transform.position.z), Quaternion.identity) as GameObject;
				Shaker.shakeIt();
				//vehicleDeath();
			}
		}
		
		
		
	
	}
}
